import React, { Component ,Fragment} from 'react';
import TodoListItem from './todoListItem';
import axios from 'axios'
import './style.css'
class TodoList extends Component {
	constructor(props){
		super(props)
		this.state={
			inputValue:'',
			list:[]
		}
		this.handleInputChange=this.handleInputChange.bind(this);
		this.handleBtnClick=this.handleBtnClick.bind(this);
		this.handleDelete=this.handleDelete.bind(this)
	}

	componentDidMount(){
		axios.get('/api/todolist').then((res)=>{
			this.setState(()=>({
				list:[...res.data]
			}))
		}).catch(()=>{
			console.log(`error`)
		})
	}
	render() {
		return (
			<Fragment>
				<div>
					{/* 这是一个输入框 */}
					<label htmlFor="insertArea">姓名</label>
					<input id="insertArea" className='input' type="text" 
						value={this.state.inputValue} 
						onChange={this.handleInputChange}
					/>
					<button onClick={this.handleBtnClick}>提交</button>
				</div>
				<ul >
				{this.getTodoItem()}
				</ul>
			</Fragment>
		)
	}
	getTodoItem(){
		return this.state.list.map((item,index)=>{
			return(
				<div key={index}>
					<TodoListItem itemDelete={this.handleDelete} content={item} index={index} />
					{/*<li key={index} onClick={this.handleDelete.bind(this,index)}
					dangerouslySetInnerHTML={{__html:item}}
					>
					</li>
					*/}
				</div>

			) 
			
		})
	}
	handleInputChange(e){
		console.log(e.target.value)
		let val=e.target.value
		this.setState(()=>({
			inputValue:val
		}))
		// this.setState({
		// 	inputValue:e.target.value
		// })
	}

	handleBtnClick(){
		const list=this.state.list
		list.push(this.state.inputValue)
		this.setState(()=>({
			list:list,
			inputValue:''
		}))
		// this.setState({
		// 	// list:[...this.state.list,this.state.inputValue]
		// 	list:a,
		// 	inputValue:''
		// })

	}
	handleDelete(index){
		let list=[...this.state.list]
		list.splice(index,1)
		console.log(list)
		this.setState(()=>({
			list:list
		}))
	}
}
export default TodoList;